package com.example.month11.okhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;

import com.example.recyclerview01.R;
import com.example.utils.L;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * 构建基类BaseRequest，可变代码，各自类自己实现。
 * 1. 拿到okHttpClient对象
 * 2. 构建Request(构建requestBody，包装requestBody)
 * 3. Call--execute()
 * 4.
 */
public class OkHttpActivity extends AppCompatActivity {
    OkHttpClient okHttpClient;
    TextView mTvResult;
    private String mBaseUrl = "http://www.imooc.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);
        mTvResult = findViewById(R.id.id_tv_result);

        okHttpClient = new OkHttpClient();  // 1.拿到okhttpClient对象
        // cookie保存在内存中。
        okHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    }

    public void onGet(View view) {
        Request.Builder builder = new Request.Builder();  // 2.构建request
        Request request = builder.get().url("http://www.imooc.com").build();
        executeRequest(request);
    }

    // 执行网络请求。
    private void executeRequest(Request request) {
        Call call = okHttpClient.newCall(request);  // 3.将request封装为call
        // call.execute(); 同步直接执行
        // 4.异步执行call
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                L.e("onFailure：" + e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // 支持大文件的下载。InputStream is = response.body().byteStream();

                String result = response.body().string();
                L.e("onResponse:" + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvResult.setText(result);
                    }
                });
            }
        });
    }

    public void doPost(View view) {
        FormEncodingBuilder requestBodyBuilder = new FormEncodingBuilder();
        RequestBody requestBody = requestBodyBuilder
                .add("username", "tom")
                .add("password", "123")
                .build();
        Request.Builder builder = new Request.Builder();  // 2.构建request
        Request request = builder.get().url(mBaseUrl + "login")
                .post(requestBody).build();
        executeRequest(request);
    }

    public void doPostString() {
        // 传输json数据给服务器。
        String payload = "{username:tom,password:234}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), payload);
        Request.Builder builder = new Request.Builder();  // 2.构建request
        Request request = builder.get().url(mBaseUrl + "login")
                .post(requestBody).build();
        executeRequest(request);
    }

    // 上传file到服务端。
    public void doPostFile() {
        File file = new File(Environment.getExternalStorageDirectory(), "banner2.jpg");
        if (!file.exists()) {
            L.e(file.getAbsolutePath() + " not existed!!!");
            return;
        }
        // mine Type
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        Request.Builder builder = new Request.Builder();  // 2.构建request
        Request request = builder.get().url(mBaseUrl + "login")
                .post(requestBody).build();
        executeRequest(request);
    }

    // post 上传文件 MultipartFromPart， 上传进度百分比
    public void doUpload() {
        File file = new File(Environment.getExternalStorageDirectory(), "banner2.jpg");
        if (!file.exists()) {
            L.e(file.getAbsolutePath() + " not existed!!!");
            return;
        }
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestFile = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("username", "Tom")
                .addFormDataPart("password", "123")
                .addFormDataPart("mPhoto", "h.jpg", requestFile)
                .build();
        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener() {
            @Override
            public void onRequestProgress(long byteWritten, long contentLength) {
                // 回调到上传文件的进度
                L.e("上传进度：" + byteWritten + "/" + contentLength);
            }
        });
        Request.Builder builder = new Request.Builder();  // 2.构建request
        Request request = builder.get().url(mBaseUrl + "uploadInfo")
                .post(countingRequestBody).build();
        executeRequest(request);
    }

    // post 下载文件
    public void doDownload() {
        Request.Builder builder = new Request.Builder();  // 2.构建request
        Request request = builder.get().url(mBaseUrl + "files/hyman.jpg").build();
        executeRequest(request);

        Call call = okHttpClient.newCall(request);  // 3.将request封装为call
        // call.execute(); 同步直接执行
        // 4.异步执行call
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                L.e("onFailure：" + e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                long totalLen = response.body().contentLength();
                long sum = 0L; // 已经加载的总长度

                // 支持大文件的下载。
                InputStream is = response.body().byteStream();
                int len = 0;
                byte[] buf = new byte[128];
                File file = new File(Environment.getExternalStorageState(), "hyman1111.jpg");
                FileOutputStream fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    sum += len; // 用于计算下载进度
                }
                fos.flush();
                fos.close();
                is.close();
                L.e("download success.");

                // InputStream is = response.body().byteStream();
                // 大图片，先保存到本地，然后借助inSampleSize，BitmapFactory.Options加载图片。
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // mIv.setImageBitmap(bitmap);
                    }
                });
            }
        });
    }

}
